package handler

import (
	"google.golang.org/protobuf/reflect/protoreflect"
	"google.golang.org/protobuf/types/dynamicpb"
	"sen-golang-study/go_game_study/hero_story_go_server/biz_server/service/user/user_lazy_save_service"
	"sen-golang-study/go_game_study/hero_story_go_server/biz_server/service/user/userdata"
	"sen-golang-study/go_game_study/hero_story_go_server/common/server_msg/proto_msg"

	"sen-golang-study/go_game_study/hero_story_go_server/common/lazy_save_service"
)

// 用户攻击指令处理器
func handleUserAttack(ctx CmdContext, pbMsgObj *dynamicpb.Message) {
	if nil == ctx ||
		nil == pbMsgObj {
		return
	}

	userAttkCmd := &proto_msg.UserAttkCmd{}

	pbMsgObj.Range(func(f protoreflect.FieldDescriptor, v protoreflect.Value) bool {
		userAttkCmd.ProtoReflect().Set(f, v)
		return true
	})

	userAttkResult := &proto_msg.UserAttkResult{
		AttkUserId:   ctx.GetUserId(),
		TargetUserId: userAttkCmd.TargetUserId,
	}

	ctxGroup := GetCmdContextGroup()
	ctxGroup.Broadcast(userAttkResult)

	targetUser := userdata.GetUserGroup().GetByUserId(userAttkCmd.GetTargetUserId())

	if nil == targetUser {
		return
	}

	var subtractHp uint32 = 10
	targetUser.CurHp -= subtractHp

	userSubtractHpResult := &proto_msg.UserSubtractHpResult{
		SubtractHp:   subtractHp,
		TargetUserId: userAttkCmd.TargetUserId,
	}

	ctxGroup.Broadcast(userSubtractHpResult)

	userLazySaver := user_lazy_save_service.GetUserLazySaver(targetUser)

	// 执行延迟保存
	lazy_save_service.SaveOrUpdate(userLazySaver)
}
